package com.wingsboat.factory.support;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FactoryBeanRegistrySupport FactoryBean 注册表
 */
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry{
    private final Map<String,Object> factoryBeanObjectCache = new ConcurrentHashMap<>();

    protected Object getCacheObjectForFactoryBean(String beanName){
        return factoryBeanObjectCache.get(beanName);
    }

    protected Object getObjectFromFactoryBean(FactoryBean factoryBean,String beanName){
        Object object = null;
        if(factoryBean.isSingleton()){
            object = this.factoryBeanObjectCache.get(beanName);
            if(null == object){
                object = doGetObjectFromFactoryBean(factoryBean,beanName);
                factoryBeanObjectCache.put(beanName,object);
            }
        }else{
            object = doGetObjectFromFactoryBean(factoryBean,beanName);
        }
        return object;
    }

    private Object doGetObjectFromFactoryBean(FactoryBean factoryBean, String beanName) {
        try {
            Object object = factoryBean.getObject();
            return object;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
